<?php

namespace app\common\model;

use app\lib\enum\Status;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import("wechat.Pay");

class PySearchLog extends BaseModel
{
    //绑定年份
    public function bindYear()
    {
        return $this->hasOne("PyAttr", "attr_id", "slo_year_id");
    }

    //绑定地区
    public function bindLocation()
    {
        return $this->hasOne("PyAttr", "attr_id", "slo_location_id");
    }

    //判断是否搜索过
    public function checkSearch($inputData)
    {
        //判断当前的搜索条件是否存在与记录中 的 condition
        $condition = $this->getCondition($inputData);

        //进行查找
        try {
            //查找出最新的记录
            $result = $this->where($condition)
                ->order("slo_id", "desc")
                ->find();
        } catch (Exception $exception) {
            return "查询异常" . $exception->getMessage();
        }


        //对结果进行判断
        //判断是否下载过
        if (!$result) {
            return "该搜索条件未搜索过";
        }
        //判断是否支付成功
        if ($result['slo_pay_status'] != Status::paySuccess) {
            return "支付未成功";
        }

        //判断是否过期(单位：分钟)
        $web_search_time = model("CmsWebsite")->getCacheData("web_search_time");
        if ($result['slo_create_time'] + ($web_search_time * 60) < time()) {
            return "查询时间过期";
        } else {
            //如果可以下载，直接把订单号返回回去
            //控制器端根据不同的返回类型判断不同的结果
            return [
                "status" => 1,
                "slo_wechat_code" => $result['slo_wechat_code']
            ];
        }

    }




    //插入数据，生成支付参数
    public function getPay($inputData)
    {
        $usr_openid = session("userInfo")['data']['usr_openid'];
        $inputData = $this->assembleInsertData($inputData);

        //开启事务插入数据
        Db::startTrans();
        try {
            $result = $this->insert($inputData);
        } catch (Exception $exception) {
            Db::rollback();
            return "数据插入异常" . $exception->getMessage();
        }
        if (!$result) {
            return "数据插入失败";
        }

        //数据插入成功返回支付参数
        //获取支付参数
        $url = $this->getNotifyUrl(); //支付结果回调地址

        $tempData = [
            //订单号
            "tradeNo" => $inputData['slo_wechat_code'],
            //支付金额
            //TODO::修改金额
//                "totalFee"=>(int)$inputData['slo_pay_num']*100,
            "totalFee" => 1,
            //回调地址
            "notifyUrl" => $url
        ];
        Log::write("回调地址" . $url);

        //获取支付参数数据
        $code = \Pay::getPayCode($tempData, $usr_openid);
        if (!$code) {
            Db::rollback();
            return "支付参数获取失败";
        } else {
            Db::commit();
            //创建该订单号的标识文件，用于检验是否支付成功
            $this->createTagsFile($inputData['slo_wechat_code']);
            return [
                "status" => "success",
                "msg" => "支付参数获取成功",
                "data" => $code,
                "slo_wechat_code" => $inputData['slo_wechat_code']
            ];
        }
    }


    //创建标识文件
    //根据微信订单号
    public function createTagsFile($slo_wechat_code)
    {
        $tagsFilePath = config("setting.tagsFilePath");
        $filePath = $tagsFilePath . $slo_wechat_code;
        try {
            $result = fopen($filePath, "w");
        } catch (Exception $exception) {
            Log::write("TReportLog createTagsFile：" . $exception->getMessage());
            return $exception->getMessage();
        }
        return true;
    }

    //获取回调地址
    public function getNotifyUrl()
    {
        $scheme = $_SERVER['REQUEST_SCHEME'];
        if (strtoupper($scheme) == "HTTP") {
            return "http://" . $_SERVER['HTTP_HOST'] . "/search/Common/notify"; //支付结果回调地址
        } else {
            return "https://" . $_SERVER['HTTP_HOST'] . "/search/Common/notify"; //支付结果回调地址
        }
    }

    //根据指定的订单号，判断该订单号是否有效（查看数据）
    public function checkWechatCode($wechatCode)
    {
        //获取信息
        $logInfo = $this->where("slo_wechat_code", "=", $wechatCode)->find();
        if (!$logInfo) {
            return "不存在该订单号";
        }

        //如果还订单号是免费查询的订单号，则不需要校验支付是否成功，但还是要校验查询时间是否失效
        if ($logInfo['slo_pay_status']!=Status::freeGet&&$logInfo['slo_pay_status'] != Status::paySuccess) {
            return "未支付成功";
        }


        $web_search_time = model("CmsWebsite")->getCacheData("web_search_time");
        if ($logInfo['slo_create_time'] + ($web_search_time * 60) < time()) {
            return "查询时间过期";
        }
        //条件通过，返回一个数组
        //控制器根据返回对象的类型 ，做出不同的操作
        return [
            "status" => "success"
        ];
    }

    //判断当前用户是否有免费查询的机会，如果有，在判断当前用户在当前条件下是否已经搜索过且未过期
    public function checkFreeGet($inputData){
        $condition=$this->getCondition($inputData);
        $condition['slo_pay_status']=['eq',Status::freeGet];
        //进行查找
        try {
            //查找出最新的记录
            $result = $this->where($condition)
                ->order("slo_id", "desc")
                ->find();
        } catch (Exception $exception) {
            return "查询异常" . $exception->getMessage();
        }

        //该条件是否免费搜索过
        //直接询问用户是否愿意花费1次免费搜索的机会搜索该条件
        if(!$result){
            return "未免费搜索过";
        }

        //判断搜索是否过期
        //判断是否过期(单位：分钟)
        $web_search_time = model("CmsWebsite")->getCacheData("web_search_time");
        if ($result['slo_create_time'] + ($web_search_time * 60) < time()) {
            //查询时间过期，询问用户是否愿意花费1次免费搜索的机会搜索该条件
            return "查询时间过期";
        } else {
            //用户可以接着免费搜索该条件，且不花费免费搜素的机会（用户在很短时间内已经使用过一次机会用来搜索这个条件了）
            //返回相应的订单号
            return [
                "slo_wechat_code"=>$result['slo_wechat_code']
            ];
        }


    }




    //获取能够免费搜索的数量
    //结果=系统设定免费搜索数量 - 已经免费的数量
    public function getFreeNum()
    {
        $web_search_free_num = model("CmsWebsite")->getCacheData("web_search_free_num");
        $usr_id = session("userInfo")['data']['usr_id'];
        $usr_openid = session("userInfo")['data']['usr_openid'];
        $condition = [];
        $condition['slo_user_id'] = ['eq', $usr_id];
        $condition['slo_user_openid'] = ['eq', $usr_openid];
        $condition['slo_pay_status'] = ['eq', Status::freeGet];
        try {
            $countData = $this->field("count(*)")
                ->where($condition)
                ->select();
        } catch (Exception $exception) {
            Log::write("PySearchLog getFreeNum:" . $exception->getMessage());
            return 0;
        }
        return (int)($web_search_free_num - $countData[0]['count(*)']);
    }




    //插入免费查询的数据
    public function createFreeLog($inputData){
        //获取要插入的数据
        $inputData=$this->assembleInsertData($inputData);
        //将数据中的支付状态改为 免费查询标志
        $inputData['slo_pay_status']=Status::freeGet;
        //进行数据插入
        try{
            $result=$this->insert($inputData);
        }catch (Exception $exception){
            return "数据插入异常".$exception->getMessage();
        }

        return [
            "slo_wechat_code"=>$inputData['slo_wechat_code']
        ];
    }



















    //产生condition
    //判断用户是否搜索过该条件
    public function getCondition($inputData)
    {
        //        year=2&
        //location=1&slo_school_code=
        //&slo_school_name=&slo_profession_code=&slo_profession_name=&slo_grade_min=&slo_grade_max=&slo_position_min=&slo_position_max=
        $usr_id = session("userInfo")['data']['usr_id'];
        $usr_openid = session("userInfo")['data']['usr_openid'];


        $inputData['slo_location_id'] = $inputData['location'];
        $inputData['slo_year_id'] = $inputData['year'];
        //用户相关条件
        $condition['slo_user_id'] = $usr_id;
        $condition['slo_user_openid'] = $usr_openid;

        //过滤数据
        $data = $this->dataFilter($inputData);

        //组装condition
        $condition = [];
        foreach ($data as $key => $value) {
            $condition[$key] = ['eq', $value];
        }
        return $condition;

    }




    //组装要插入的log表的数据，根据前台传入的数据
    public function assembleInsertData($inputData)
    {
        $usr_id = session("userInfo")['data']['usr_id'];
        $usr_openid = session("userInfo")['data']['usr_openid'];

        //组装要插入的数据
        $inputData['slo_location_id'] = $inputData['location'];
        $inputData['slo_year_id'] = $inputData['year'];
        $inputData['slo_user_id'] = $usr_id;
        $inputData['slo_user_openid'] = $usr_openid;
        $inputData['slo_create_time'] = time();
        $inputData['slo_pay_status'] = Status::noPay;
        $inputData['slo_wechat_code'] = $this->getWechatCode($inputData);
        $inputData['slo_pay_num'] = model("CmsWebsite")->getCacheData('web_search_fee');
        //过滤数据
        $inputData = $this->dataFilter($inputData);
        return $inputData;
    }


    //生成微信订单号，长度小于32
    public function getWechatCode($inputData)
    {
        $code = input("location") . "_" . $inputData['year'] . time() . rand(11111, 99999);
        return $code;
    }

}
